package com.jdbc.dataAccess;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public abstract class Database {

      public static final int OracleDatabase = 0;
      protected ConnectionSettings connSettings;
      protected String connectionString = null;

      public Database(String connectionString) {
            this.connectionString = connectionString;
      }

      public Database(ConnectionSettings connSettings) {
            this.connSettings = connSettings;
      }

      protected ConnectionSettings getConnSettings() {
            return this.connSettings;
      }

      public String getConnectionString() {
            return connSettings.toString();
      }

      public ResultSet executeQuery(String sql) throws Exception {

            if (sql == null)  throw new NullPointerException("Parameter sql is null");
            
            Connection connection = null;
            try {
                  connection = DBConnection.getConnection(connSettings);
            } catch (Exception ex) {
                  ex.printStackTrace();
                  throw ex;
            }

            if (connection == null)  throw new NullPointerException("Connection is null");
            
            try {
                  Statement oStmt = connection.createStatement();
                  return oStmt.executeQuery(sql);

            } catch (Exception ex) {
                  throw ex;
            } finally {
                  
                  if (connection != null && !connection.isClosed()) {
                        connection.close();
                  }
                  
            }
      }

      public int executeUpdate(String sql) throws Exception {
            
            if (sql == null)  throw new NullPointerException("Parameter sql is null");
            
            Connection connection = null;
            try {
                  connection = DBConnection.getConnection(connSettings);
            } catch (Exception ex) {
                  ex.printStackTrace();
                  throw ex;
            }

            if (connection == null)  throw new NullPointerException("Connection is null");
            
            try {
                  Statement oStmt = connection.createStatement();
                  return oStmt.executeUpdate(sql);

            } catch (Exception ex) {
                  throw ex;
            } finally {
                  
                  if (connection != null && !connection.isClosed()) {
                        connection.close();
                  }
                  
            }
      }
      
      public abstract void executeProcedure(DBProcedure cmd);

}
